package com.lulin.mall.auth.server.controller;

import com.alibaba.fastjson.JSON;
import com.lulin.common.constant.AuthConstant;
import com.lulin.common.utils.HttpUtils;
import com.lulin.common.utils.R;
import com.lulin.common.vo.MemberVo;
import com.lulin.mall.auth.server.fegin.MemberFeignService;
import com.lulin.mall.auth.server.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * OAuth2.0认证相关
 *
 * @author lulin
 * @date 2022/12/12 10:42
 */
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 微博登录
     */
    @GetMapping("/oauth/weibo/success")
    public String weiboOAuth2(@RequestParam("code") String code, HttpSession session) throws Exception {
        HashMap<String, String> param = new HashMap<>();
        //封装请求参数（必填的）
        param.put("client_id", "2867848428");
        param.put("client_secret", "47ec6bb6086d9a4b9bdaeea7a6f19a8d");
        param.put("grant_type", "authorization_code");
        param.put("redirect_uri", "http://auth.lulin.com/oauth/weibo/success");//重定向地址（回调的）
        param.put("code", code);//code

        //根据code，获取token（服务的调用 ）
        //https://api.weibo.com/oauth2/access_token?参数
        HttpResponse post = HttpUtils.doPost("https://api.weibo.com",
                "/oauth2/access_token",
                "post",
                new HashMap<>(),
                null,
                param
        );
        //获取返回状态
        int statusCode = post.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            //说明获取token失败，跳转回登录页面
            return "redirect:http://auth.lulin.com/login.html";
        }
        //否则，获取token成功
        String json = EntityUtils.toString(post.getEntity());
        SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

        //远程调用微博登录方法
        R r = memberFeignService.weiboSocialLogin(socialUser);
        if (r.getCode() != 0) {
            // 登录错误
            return "redirect:http://mall.lulin.com/login.html";
        }
        String entityJson = (String) r.get("entity");
        MemberVo memberVo = JSON.parseObject(entityJson, MemberVo.class);
        //测试session
        session.setAttribute(AuthConstant.AUTH_SESSION_REDIS, memberVo);

        //注册成功后，跳转到商城的首页
        return "redirect:http://mall.lulin.com/home.html";
    }



    /**
     * 微博登录
     */
    @GetMapping("/oauth/qq/success")
    public String weiboOAuth2(@RequestParam("code") String code){

        return null;
    }
}
